package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.POJO.Permission;
import com.itheima.POJO.Role;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageResult getrole(Map map) {
        String queryString = (String) map.get("queryString");
        System.out.println(queryString);
        PageHelper.startPage((Integer) map.get("currentPage"),(Integer)map.get("pageSize"));
        Page<Role>page= roleMapper.getrole(queryString);
        return  new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Permission> getpermissions() {
        List<Permission>list=permissionMapper.getpermissions();
        return list;
    }

    @Override
    public List<Permission> addrole(Integer[] checkitemIds, Role role) {
        roleMapper.addRole(role);
        for (Integer checkitemId : checkitemIds) {
            roleMapper.addRolePermission(role.getId(),checkitemId);
        }
        return null;
    }

    @Override
    public void deleteRole(Integer id) {
        Integer countUser=roleMapper.findUserCountById(id);
        if (countUser>0){
            throw new RuntimeException("角色已关联用户,删除失败");
        }
        Integer countMenu=roleMapper.findMenuCountById(id);
        if (countMenu>0){
            throw new RuntimeException("角色已关联菜单,删除失败");
        }
        roleMapper.deleteRolePermissionByRoleId(id);
        roleMapper.deleteRoleByRoleId(id);
    }

    @Override
    public Role findRoleById(Integer id) {
        Role role=roleMapper.findRoleByRoleId(id);
        return role;
    }

    @Override
    public void edit(Integer[] checkitemIds, Role role) {
        roleMapper.deleteRolePermissionByRoleId(role.getId());
        for (Integer checkitemId : checkitemIds) {
            roleMapper.addRolePermission(role.getId(),checkitemId);
        }
        roleMapper.updateRole(role);
    }

    @Override
    public Result findAllRole() {
        try {
            List<Role> roles= roleMapper.findAllRole();
            return new Result(true, "获取角色信息成功",roles);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,"获取角色信息失败");
    }
}
